package com.toutiao.cut.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.toutiao.cut.SemanticCutter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

public class DocumentProcessServlet extends HttpServlet {

    private static final long serialVersionUID = -43361324548827880L;

    private SemanticCutter cut;
    private Gson gson = new Gson();

    public DocumentProcessServlet(SemanticCutter c){
        cut = c;
    }

    @Override
    protected void doGet(HttpServletRequest rq, HttpServletResponse rp)
            throws ServletException,IOException{
        process(rq,rp);
    }

    @Override
    protected void doPost(HttpServletRequest rq, HttpServletResponse rp)
            throws ServletException,IOException{
        process(rq,rp);
    }

    private String process_cut(String line) {
        StringBuilder buffer = new StringBuilder();
        List<String> ns = cut.process(line);
        for (String n : ns){
            buffer.append(n).append(" ");
        }
        return buffer.toString().trim();
    }

    void process(HttpServletRequest rq, HttpServletResponse rp)
        throws ServletException,IOException {

        rq.setCharacterEncoding("UTF-8");
        rp.setCharacterEncoding("UTF-8");
        rp.setContentType("text/html");

        String data = rq.getParameter("data");


        Map<String,String> map = gson.fromJson(data, new TypeToken<Map<String,String>>() {}.getType());

        String title = "";
        if (map.containsKey("title")){
            title = map.get("title");
        }
        String content = "";
        if (map.containsKey("txt_content")){
            content = map.get("txt_content");
        }

        String cut_title = process_cut(title);
        String[] split_content = content.split("\n");
        StringBuilder cut_content = new StringBuilder();
        for (String line: split_content){
            cut_content.append(process_cut(line)).append("\n");
        }

        Map<String,String> res_map = new HashMap<String,String>();
        res_map.put("cut_title",cut_title);
        res_map.put("cut_content",cut_content.toString().trim());

        String res = gson.toJson(res_map);

        PrintWriter out = rp.getWriter();

        out.println(res);
    }

}
